package com.junzhiit.nengji.cms.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.netflix.hystrix.exception.HystrixBadRequestException;

import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;

@Configuration
public class FeignConfig {

	@Bean
	public ErrorDecoder errorDecoder() {
		return new FeignErrorDecoder();
	}
	
	private class FeignErrorDecoder implements feign.codec.ErrorDecoder{
		
		protected final Logger logger = LoggerFactory.getLogger(this.getClass());
		
		@Override
		public Exception decode(String methodKey, Response response) {
			try {
				String body = Util.toString(response.body().asReader());
				return new HystrixBadRequestException(body);
			} catch (Exception e) {
				logger.error("feign error解码器, 解码自定义异常失败！");
				logger.error(e.getMessage());
			}
			return feign.FeignException.errorStatus(methodKey, response);
		}
	}
}
